$(document).ready(function () {
    window.s = {};
    var owner = $("h4").text();
    console.log("yuanxing", window.s);
    $(".friend-target").click(function () {
        let idd = $(this).attr('data-value');// 节点的value属性
        let name = $(this).children("span:first-child").text();
        var to_user = $(".to-user");
        to_user.attr("data-value", idd);
        to_user.text(name);
        console.log("idd", idd);
        getWebsocket(owner, name, idd)
    });
    $("#content-send").click(function () {
        if (!$("#content-edit").val()) {
            alert("消息不能为空");
            return false
        }
        if (!$(".to-user").text()) {
            alert("请选择聊天对象");
            return false
        }
        let message = $("#content-edit").val();
        let idd = $(".to-user").attr("data-value");// 节点的value属性
        let name = $(".to-user").text();
        if (!window.s[owner + "_" + name]) {
            getWebsocket(owner, name, idd);
        }
        window.s[owner + "_" + name].send(message);
        $("#content-edit").empty()
    })
});

function getWebsocket(owner, uname, uid) {
    var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws";
    var ws = new WebSocket(ws_scheme + "://" + window.location.host + "/chat/" + uid);
    if (!window.s[owner + "_" + uname]) {
        window.s[owner + "_" + uname] = ws
    }
    ws.onopen = function (ev) {
        console.log('websocket is opening')
    };
    ws.onclose = function (ev) {
        ws.close();
        delete window.s[owner + "_" + uname]
    };
    ws.onerror = function (ev) {
        console.log('websocket is on error')
    };
    ws.onmessage = handleMessage;
}

function handleMessage(ev) {
    console.log('message: ' + ev.data);
    let message_series = ev.data.split("--");
    console.log(message_series[3]);
    let huser = document.getElementsByTagName("h4")[0].innerText;
    if (message_series[0] === huser) {
        //    是自己
        let owner_html = "<div class='owner'>" +
            "             <span class='date'>" + message_series[1] + "</span>" +
            "             <p>" + message_series[0] + "</p>" +
            "             <span class='message-content'>" + message_series[3] + "</span>" +
            "             </div>"
        // $(".content-box").append()
        let content_box = $(".content-box");
        // 往最后添加
        content_box.append(owner_html);
    }
    else {
        let other_html = "<div class='other'>" +
            "             <span class='date'>" + message_series[1] + "</span>" +
            "             <p>" + message_series[0] + "</p>" +
            "             <span class='message-content'>" + message_series[3] + "</span>" +
            "             </div>";
        $(".content-box").append(other_html);
    }
}